﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using RMS.Common;
using RMS.DB;

namespace RMS
{
    public partial class frmInventory : ICommonForm
    {
        private readonly string IdFromListItem;
        private readonly InventoryMng inventoryMng = new InventoryMng();
        private readonly SupplierMng supplierMng = new SupplierMng();
        private List<string> listItemsId = new List<string>();
        private string supplierID = "";
        private string imageFilename = "";

        public frmInventory()
        {
            InitializeComponent();
            listItemsId = inventoryMng.GetAllItemsId();
            browseImageDialog = new OpenFileDialog();
        }

        public frmInventory(string xID)
        {
            InitializeComponent();
            IdFromListItem = xID;
            listItemsId = inventoryMng.GetAllItemsId();
            browseImageDialog = new OpenFileDialog();
        }

        private void LoadItemFromList(string id)
        {
            Inventory item = inventoryMng.GetInventoryByElements(id);
            if (item == null)
            {
                MessageBox.Show(Constants.Msg.NotItemExist);
                return;
            }
            txtID.Text = item.ID;
            txtName.Text = item.Name;
            txtCategory.Text = item.Category;
            txtDesc.Text = item.Description;
            txtSalePrice.Text = Convert.ToString(item.SalePrice);
            txtQuantity.Text = Convert.ToString(item.Quantity);
            BindSupplierData(item.SupplierID);
            txtStyleNo.Text = item.StyleId;
            txtUnitCost.Text = Utilities.FormatNumber(Convert.ToDecimal(item.ImportPrice), Utilities.PrecisionFormat);
            txtWeight.Text = Utilities.FormatNumber(Convert.ToDecimal(item.Weight), 3);
            txtDungtich.Text = Utilities.FormatNumber(Convert.ToDecimal(item.Volume), 0);
            //txtChiVang.Text = Utilities.FormatNumber(Convert.ToDecimal(item.Weight)/(decimal) Constants.GoldConst, 3);
            dateTimePicker1.Value = Convert.ToDateTime(item.Date);

            txtInvoiceNo.Text = item.InvoiceNo;
            txtMemoNo.Text = item.MemoNo;
            txtItemNo.Text = item.ItemNo;
            txtSupStyleNo.Text = item.StyleNo;

            try
            {
                itemImage.Image = item.Image != null ? Image.FromFile(Constants.ImageFilePath + item.Image) : null;
            }
            catch (FileNotFoundException)
            {
                itemImage.Image = null;
            }
            txtTotalPrice.Text = Utilities.FormatNumber(Convert.ToDecimal(item.TotalPrice), Utilities.PrecisionFormat);
        }

        private void btnOpenLocation_Click(object sender, EventArgs e)
        {
            var location = new DialogCategory { ShowInTaskbar = false };
            if (location.ShowDialog() == DialogResult.OK)
            {
                txtCategory.Text = location.result;
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            var frm = new frmListStock { MdiParent = ActiveForm, StartPosition = FormStartPosition.CenterScreen };
            frm.Show();
            Close();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Inventory item = inventoryMng.GetInventoryByElements(txtID.Text.Trim());
            if (item == null)
            {
                //MessageBox.Show(Constants.Msg.NotItemExist);
                btnAdd.Enabled = true;
                btnUpdate.Enabled = btnDel.Enabled = false;
                txtID.Focus();
                return;
            }
            txtName.Text = item.Name;
            txtDungtich.Text = Utilities.FormatNumber(Convert.ToDecimal(item.Volume), 0);
            txtCategory.Text = item.Category;
            txtDesc.Text = item.Description;
            txtSalePrice.Text = Utilities.FormatNumber(Convert.ToDecimal(item.SalePrice), Utilities.PrecisionFormat);
            txtQuantity.Text = Convert.ToString(item.Quantity);
            txtStyleNo.Text = item.StyleId;
            BindSupplierData(item.SupplierID);
            txtUnitCost.Text = Utilities.FormatNumber(Convert.ToDecimal(item.ImportPrice), Utilities.PrecisionFormat);
            txtWeight.Text = Utilities.FormatNumber(Convert.ToDecimal(item.Weight), 3);
            //txtChiVang.Text = Utilities.FormatNumber(Convert.ToDecimal(item.Weight)/(decimal) Constants.GoldConst, 3);
            dateTimePicker1.Value = Convert.ToDateTime(item.Date);

            txtInvoiceNo.Text = item.InvoiceNo;
            txtMemoNo.Text = item.MemoNo;
            txtItemNo.Text = item.ItemNo;
            txtSupStyleNo.Text = item.StyleNo;

            try
            {
                itemImage.Image = item.Image != null ? Image.FromFile(Constants.ImageFilePath + item.Image) : null;
            }
            catch (FileNotFoundException)
            {
                itemImage.Image = null;
            }
            txtTotalPrice.Text = Utilities.FormatNumber(Convert.ToDecimal(item.TotalPrice), Utilities.PrecisionFormat);
            btnAdd.Enabled = false;
            btnUpdate.Enabled = btnDel.Enabled = true;
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            browseImageDialog = new OpenFileDialog();
            browseImageDialog.Title = @"Select product image:";
            browseImageDialog.InitialDirectory = Application.StartupPath + Constants.ImageFilePath;
            browseImageDialog.Filter =
            @"Image files (*.jpg; *.png; *.bmp; *.gif)|*.jpg;*.jpeg;*.png;*.bmp;*.gif|All files (*.*)|*.*";
            browseImageDialog.FilterIndex = 1;
            browseImageDialog.RestoreDirectory = true;
            if (browseImageDialog.ShowDialog() == DialogResult.OK)
            {
                itemImage.Image = Image.FromFile(browseImageDialog.FileName);
            }
        }

        private void btnDelImage_Click(object sender, EventArgs e)
        {
            imageFilename = "noimage";
            itemImage.Image = null;
            browseImageDialog = new OpenFileDialog();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {

                string fileName;
                try
                {
                    fileName = string.IsNullOrEmpty(browseImageDialog.SafeFileName) ? imageFilename : browseImageDialog.SafeFileName;
                }
                catch (NullReferenceException)
                {
                    fileName = "";
                }
                int qty = string.IsNullOrEmpty(txtQuantity.Text.Trim()) ? 0 : Convert.ToInt32(txtQuantity.Text.Trim());
                decimal weight = string.IsNullOrEmpty(txtWeight.Text.Trim()) ? 0 : Convert.ToDecimal(txtWeight.Text.Trim());
                decimal volume = string.IsNullOrEmpty(txtDungtich.Text.Trim()) ? 0 : Convert.ToDecimal(txtDungtich.Text.Trim());
                decimal importPrice = string.IsNullOrEmpty(txtUnitCost.Text.Trim())
                ? 0
                : Convert.ToDecimal(txtUnitCost.Text.Trim());
                decimal totalPrice = string.IsNullOrEmpty(txtTotalPrice.Text.Trim())
                ? 0
                : Convert.ToDecimal(txtTotalPrice.Text.Trim());
                decimal salePrice = string.IsNullOrEmpty(txtSalePrice.Text.Trim())
                ? 0
                : Convert.ToDecimal(txtSalePrice.Text.Trim());
                if (inventoryMng.AddInventoryItem(txtName.Text.Trim(), volume, txtID.Text.Trim(), supplierID, txtCategory.Text.Trim(),
                txtStyleNo.Text.Trim(), qty,
                dateTimePicker1.Value, txtDesc.Text.Trim(), salePrice,
                weight, importPrice, fileName, totalPrice, txtInvoiceNo.Text.Trim(),
                txtMemoNo.Text.Trim(), txtItemNo.Text.Trim(), txtSupStyleNo.Text.Trim()))
                {
                    if (!string.IsNullOrEmpty(browseImageDialog.FileName) && string.IsNullOrEmpty(imageFilename))
                        File.Copy(browseImageDialog.FileName,
                        Application.StartupPath + "\\" + Constants.ImageFilePath + browseImageDialog.SafeFileName,
                        true);
                    MessageBox.Show(Constants.Msg.AddNewSuccessful);
                    ClearAllField();
                }
                listItemsId = inventoryMng.GetAllItemsId();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Loi khi luu san pham: " + ex.Message);
            }
        }

        private void frmInventory_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(IdFromListItem))
            {
                LoadItemFromList(IdFromListItem);
                btnAdd.Enabled = false;
                btnUpdate.Enabled = btnDel.Enabled = true;
            }
            else
            {
                btnAdd.Enabled = true;
                btnUpdate.Enabled = btnDel.Enabled = false;
            }
            txtID.Focus();
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Constants.Msg.DeleteItem, "Chú ý", MessageBoxButtons.YesNo) != DialogResult.Yes)
                return;
            if (inventoryMng.DeleteItem(txtID.Text.Trim()))
            {
                MessageBox.Show(Constants.Msg.DeleteSuccessful);
                ClearAllField();
                listItemsId = inventoryMng.GetAllItemsId();
                btnAdd.Enabled = true;
                btnUpdate.Enabled = btnDel.Enabled = false;
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {

                string fileName;
                try
                {
                    fileName = string.IsNullOrEmpty(browseImageDialog.SafeFileName) ? imageFilename : browseImageDialog.SafeFileName;
                }
                catch (NullReferenceException)
                {
                    fileName = "";
                }
                int qty = string.IsNullOrEmpty(txtQuantity.Text.Trim()) ? 0 : Convert.ToInt32(txtQuantity.Text.Trim());
                decimal weight = string.IsNullOrEmpty(txtWeight.Text.Trim()) ? 0 : Convert.ToDecimal(txtWeight.Text.Trim());
                decimal volume = string.IsNullOrEmpty(txtDungtich.Text.Trim()) ? 0 : Convert.ToDecimal(txtDungtich.Text.Trim());
                decimal importPrice = string.IsNullOrEmpty(txtUnitCost.Text.Trim())
                ? 0
                : Convert.ToDecimal(txtUnitCost.Text.Trim());
                decimal totalPrice = string.IsNullOrEmpty(txtTotalPrice.Text.Trim())
                ? 0
                : Convert.ToDecimal(txtTotalPrice.Text.Trim());
                decimal salePrice = string.IsNullOrEmpty(txtSalePrice.Text.Trim())
                ? 0
                : Convert.ToDecimal(txtSalePrice.Text.Trim());
                if (inventoryMng.UpdateItem(txtName.Text.Trim(), volume, txtID.Text.Trim(), supplierID, txtCategory.Text.Trim(),
                txtStyleNo.Text.Trim(), qty,
                dateTimePicker1.Value, txtDesc.Text.Trim(), salePrice,
                weight, importPrice, fileName, totalPrice, txtInvoiceNo.Text.Trim(),
                txtMemoNo.Text.Trim(), txtItemNo.Text.Trim(), txtSupStyleNo.Text.Trim()))
                {
                    if (!string.IsNullOrEmpty(browseImageDialog.FileName) && string.IsNullOrEmpty(imageFilename))
                        File.Copy(browseImageDialog.FileName,
                        Application.StartupPath + "\\" + Constants.ImageFilePath + browseImageDialog.SafeFileName,
                        true);
                    MessageBox.Show(Constants.Msg.UpdateSuccessful);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Loi khi luu san pham: " + ex.Message);
            }
            
        }

        private void ClearAllField()
        {
            txtMemoNo.Text =
            txtDungtich.Text =
            txtName.Text =
            txtInvoiceNo.Text =
            txtItemNo.Text =
            txtSupStyleNo.Text =
            txtCategory.Text =
            txtDesc.Text =
            txtID.Text =
            txtSalePrice.Text =
            txtStyleNo.Text =
            txtSuppy.Text =
            txtUnitCost.Text =
            txtTotalPrice.Text =
            txtInvoiceNo.Text =
            txtMemoNo.Text =
            txtItemNo.Text =
            txtSupStyleNo.Text =
            //txtChiVang.Text =
            txtWeight.Text = "";
            itemImage.Image = null;
            imageFilename = "";
            txtQuantity.Text = "1";
            supplierID = "";
            browseImageDialog = new OpenFileDialog();
            txtID.Focus();
        }

        private void ClearFieldButId()
        {
            txtMemoNo.Text =
            txtDungtich.Text =
            txtName.Text =
            txtInvoiceNo.Text =
            txtItemNo.Text =
            txtSupStyleNo.Text =
            txtCategory.Text =
            txtDesc.Text =
            txtSalePrice.Text =
            txtStyleNo.Text =
            txtSuppy.Text =
            txtUnitCost.Text =
            //txtChiVang.Text =
            txtTotalPrice.Text =
            txtInvoiceNo.Text =
            txtMemoNo.Text =
            txtItemNo.Text =
            txtSupStyleNo.Text =
            txtWeight.Text = "";
            imageFilename = "";
            itemImage.Image = null;
            txtQuantity.Text = "1";
            supplierID = "";
        }

        private void button4_Click(object sender, EventArgs e)
        {
            var location = new DialogStyleNo { ShowInTaskbar = false };
            if (location.ShowDialog() == DialogResult.OK)
            {
                var arr = location.result.Split('*');
                txtStyleNo.Text = arr[0];
                imageFilename = arr[1];
                try
                {
                    itemImage.Image = arr[1] != null ? Image.FromFile(Constants.ImageFilePath + arr[1]) : null;
                }
                catch (FileNotFoundException)
                {
                    itemImage.Image = null;
                }
            }
        }

        //private void button1_Click(object sender, EventArgs e)
        //{
        //    var location = new DialogSalePrice { ShowInTaskbar = false };
        //    if (location.ShowDialog() == DialogResult.OK)
        //    {
        //        txtSalePrice.Text = location.result;
        //    }
        //}

        private void btnOpenSupplierDlg_Click(object sender, EventArgs e)
        {
            var location = new DialogSuppliers { ShowInTaskbar = false };
            if (location.ShowDialog() == DialogResult.OK)
            {
                supplierID = location.result;
                BindSupplierData(location.result);
            }
        }

        private void BindSupplierData(string id)
        {
            Supplier item = supplierMng.GetItemByElements(id);
            if (item == null)
            {
                txtSuppy.Text = txtInvoiceNo.Text = txtItemNo.Text = txtMemoNo.Text = txtSupStyleNo.Text = "";
                return;
            }
            txtSuppy.Text = item.Name;
            supplierID = item.ID;
        }

        private void validateNumeric(KeyPressEventArgs e)
        {
            char key = e.KeyChar;
            if ((key >= 48) && (key <= 58) || (key == 46) || key == 8 || key == 9 || (key >= 37 && key <= 40) ||
            key == 144 || key == ',')
            {
                e.Handled = false;
            }
            else
                e.Handled = true;
        }

        private void txtWeight_KeyPress(object sender, KeyPressEventArgs e)
        {
            validateNumeric(e);
        }

        private void txtUnitCost_KeyPress(object sender, KeyPressEventArgs e)
        {
            validateNumeric(e);
        }

        private void txtTotalPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            validateNumeric(e);
        }

        private void txtUnitCost_Leave(object sender, EventArgs e)
        {
            try
            {
                decimal unitCost = Convert.ToDecimal(txtUnitCost.Text.Trim());
            }
            catch (FormatException)
            {
                txtUnitCost.Text = "";
                return;
            }
            if (!string.IsNullOrEmpty(txtUnitCost.Text.Trim()))
            {
                txtUnitCost.Text = Utilities.FormatNumber(Convert.ToDecimal(txtUnitCost.Text.Trim()), Utilities.PrecisionFormat);
            }
            if (!string.IsNullOrEmpty(txtQuantity.Text.Trim()) && !string.IsNullOrEmpty(txtUnitCost.Text.Trim()))
            {
                if (string.IsNullOrEmpty(txtTotalPrice.Text.Trim()) || txtTotalPrice.Text.Trim() == "0")
                {
                    double total = Convert.ToDouble(txtUnitCost.Text) * Convert.ToDouble(txtQuantity.Text.Trim());
                    txtTotalPrice.Text = Utilities.FormatNumber(Convert.ToDecimal(total), Utilities.PrecisionFormat);
                }
            }
        }

        private void txtTotalPrice_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtTotalPrice.Text.Trim()))
            {
                try
                {
                    decimal a = Convert.ToDecimal(txtTotalPrice.Text.Trim());
                }
                catch (FormatException)
                {
                    txtTotalPrice.Text = "";
                    return;
                }
                txtTotalPrice.Text = Utilities.FormatNumber(Convert.ToDecimal(txtTotalPrice.Text.Trim()),
                Utilities.PrecisionFormat);
            }
        }

        private void txtWeight_Leave(object sender, EventArgs e)
        {
            decimal w;
            try
            {
                w = Convert.ToDecimal(txtWeight.Text.Trim());
            }
            catch (FormatException)
            {
                txtWeight.Text = "";
                return;
            }

            txtWeight.Text = Utilities.FormatNumber(w, 2);
        }

        private void txtID_Leave(object sender, EventArgs e)
        {
            string currentId = txtID.Text.Trim();
            bool flag = false;
            if (listItemsId == null)
            {
                btnAdd.Enabled = true;
                btnUpdate.Enabled = btnDel.Enabled = false;
                return;
            }
            if (!string.IsNullOrEmpty(currentId))
            {
                foreach (string _id in listItemsId)
                {
                    if (currentId == _id)
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag)
                {
                    btnAdd.Enabled = false;
                    btnUpdate.Enabled = btnDel.Enabled = true;
                }
                else
                {
                    btnAdd.Enabled = true;
                    btnUpdate.Enabled = btnDel.Enabled = false;
                    browseImageDialog = new OpenFileDialog();
                }
            }
            else
            {
                btnAdd.Enabled = true;
                btnUpdate.Enabled = btnDel.Enabled = false;
            }
        }

        //private void txtWeight_TextChanged(object sender, EventArgs e)
        //{
        //}

        //private void txtChiVang_Leave(object sender, EventArgs e)
        //{
        //    //decimal chi = 0;
        //    //try
        //    //{
        //    //    chi = Convert.ToDecimal(txtChiVang.Text.Trim());
        //    //}
        //    //catch (FormatException)
        //    //{
        //    //    txtChiVang.Text = "";
        //    //    return;
        //    //}
        //    //if (!string.IsNullOrEmpty(txtChiVang.Text.Trim()))
        //    //{
        //    //    decimal convertedVal = chi*(decimal) Constants.GoldConst;
        //    //    txtWeight.Text = Utilities.FormatNumber(convertedVal, 3);
        //    //}
        //}

        private void txtSalePrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            validateNumeric(e);
        }

        private void txtSalePrice_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtSalePrice.Text.Trim()))
            {
                try
                {
                    decimal a = Convert.ToDecimal(txtSalePrice.Text.Trim());
                }
                catch (FormatException)
                {
                    txtSalePrice.Text = "";
                    return;
                }
                txtSalePrice.Text = Utilities.FormatNumber(Convert.ToDecimal(txtSalePrice.Text.Trim()),
                Utilities.PrecisionFormat);
            }
        }

        private void txtDungtich_KeyPress(object sender, KeyPressEventArgs e)
        {
            validateNumeric(e);
        }

        private void txtDungtich_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtDungtich.Text.Trim()))
            {
                try
                {
                    decimal a = Convert.ToDecimal(txtDungtich.Text.Trim());
                }
                catch (FormatException)
                {
                    txtDungtich.Text = "";
                    return;
                }
                txtDungtich.Text = Utilities.FormatNumber(Convert.ToDecimal(txtDungtich.Text.Trim()), 0);
            }
        }

        private void txtID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                btnSearch_Click(null, null);
        }
    }
}
